package com.tanhua.commons.template;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.util.Base64Util;
import com.tanhua.commons.properties.AipFaceProperties;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * @author liuyp
 * @date 2021/01/26
 */
public class AipFaceTemplate {

    private AipFaceProperties properties;

    public AipFaceTemplate(AipFaceProperties properties) {
        this.properties = properties;
    }

    /**
     * 人脸检测
     * @param bytes 图片的字节数组
     * @return 是否检测到人脸
     */
    public boolean detect(byte[] bytes){
        // 初始化一个AipFace
        AipFace client = new AipFace(properties.getAppId(), properties.getApiKey(), properties.getSecret());

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        // options.put("face_field", "age");
        // options.put("max_face_num", "2");
        // options.put("face_type", "LIVE");
        // options.put("liveness_control", "LOW");

        // 使用百度提供的工具，把图片转换成字符串
        String image = Base64Util.encode(bytes);
        String imageType = "BASE64";

        // 人脸检测
        JSONObject res = client.detect(image, imageType, options);
        // System.out.println(res.toString(2));

        int code = res.getInt("error_code");
        return code == 0;
    }
}
